﻿using System;
using System.Collections;
using System.Threading.Tasks;
using UnityEngine;

public class HandleUseManager : SingletonMono<HandleUseManager>
{
    private Lattice targetLattice;

    private static bool _isCanceled = false;

    private async Task<Lattice> WaitSelectAsync()
    {
        var tcs = new TaskCompletionSource<Lattice>(); // 确保每次调用时重新声明
        AddWaitListener(tcs);

        try
        {
            var tcsTask = await tcs.Task;
            RemoveWaitListener(tcs);

            return tcsTask;
        }
        catch (Exception e)
        {
            if (_isCanceled)
            {
                _isCanceled = false;
                RemoveWaitListener(tcs);
                return null;
            }
            else
            {
                Debug.LogException(e);
            }
        }

        return null;
    }

    private static void AddWaitListener(TaskCompletionSource<Lattice> tcs)
    {
        EventCenter.GetInstance()
            .AddEventListener<Lattice>("ClickSelf", (lattice) =>
            {
                if (!tcs.Task.IsCompleted) tcs.SetResult(lattice);
            });
        EventCenter.GetInstance()
            .AddEventListener<Lattice>("ClickTargetLattice", (lattice) =>
            {
                if (!tcs.Task.IsCompleted) tcs.SetResult(lattice);
            });
        EventCenter.GetInstance()
            .AddEventListener<Lattice>("SpotlightChanged", (lattice) =>
            {
                if (!tcs.Task.IsCompleted)
                {
                    _isCanceled = true;
                    tcs.SetCanceled();
                }
            });
        EventCenter.GetInstance()
            .AddEventListener("SpotlightClear", () =>
            {
                if (!tcs.Task.IsCompleted)
                {
                    _isCanceled = true;
                    tcs.SetCanceled();
                }
            });
    }

    private static void RemoveWaitListener(TaskCompletionSource<Lattice> tcs)
    {
        EventCenter.GetInstance()
            .RemoveEventListener<Lattice>("ClickSelf", (lattice) =>
            {
                if (!tcs.Task.IsCompleted) tcs.SetResult(lattice);
            });
        EventCenter.GetInstance()
            .RemoveEventListener<Lattice>("ClickTargetLattice", (lattice) =>
            {
                if (!tcs.Task.IsCompleted) tcs.SetResult(lattice);
            });
        EventCenter.GetInstance()
            .RemoveEventListener<Lattice>("SpotlightChanged", (lattice) =>
            {
                if (!tcs.Task.IsCompleted)
                {
                    _isCanceled = true;
                    tcs.SetCanceled();
                }
            });
        EventCenter.GetInstance()
            .RemoveEventListener("SpotlightClear", () =>
            {
                if (!tcs.Task.IsCompleted)
                {
                    print("1");
                    _isCanceled = true;
                    tcs.SetCanceled();
                }
            });
    }

    public async Task<Lattice> PlacedChessAsync(Lattice lattice,Vector2IntMode targetPosition, BaseChessDateSo chessDate,
        Color color)
    {
        EventCenter.GetInstance().EventTrigger("SpotlightClear");
        Settings.canBeUsed = false;
        EventCenter.GetInstance()
            .EventTrigger<Lattice,Vector2IntMode, Color>("ShowTargetLattice",lattice,targetPosition, Settings.canPlaced);
        targetLattice = null;
        targetLattice = await WaitSelectAsync();
        
        EventCenter.GetInstance().EventTrigger("ClearTargetLattice");
        if (targetLattice && targetLattice!=ClickManager.GetInstance().currentLattice)
        {
            ChessManager.GetInstance().InitChess(chessDate, targetLattice.position,ChessSide.Player1);
            EventCenter.GetInstance().EventTrigger<ChessSide,int>("ReduceResources",ChessSide.Player1,
                chessDate.resourcesPoint);
            Settings.canBeUsed = true;
            return targetLattice;
        }
        else
        {
            Settings.canBeUsed = true;
            //为空,代表获取目标格子失败,返回上一步
            return null;
        }
    }
    
    public async Task<Lattice> MoveChessAsync(Lattice lattice,Vector2IntMode targetPosition, BaseChessDateSo chessDate,
        Color color)
    {
        EventCenter.GetInstance().EventTrigger("SpotlightClear");
        Settings.canBeUsed = false;
        EventCenter.GetInstance()
            .EventTrigger<Lattice,Vector2IntMode, Color>("ShowTargetLattice",lattice,targetPosition, Settings.canPlaced);
        targetLattice = null;
        targetLattice = await WaitSelectAsync();
        
        EventCenter.GetInstance().EventTrigger("ClearTargetLattice");
        if (targetLattice && targetLattice!=ClickManager.GetInstance().currentLattice)
        {
            var isAttackCharacter = ChessManager.GetInstance().MoveChess(lattice.position, targetLattice.position);
            Settings.canBeUsed = true;
            if(isAttackCharacter)
            {
                return null;
            }
            return targetLattice;
        }
        else
        {
            Settings.canBeUsed = true;
            //为空,代表获取目标格子失败,返回上一步
            return null;
        }
    }
    public static async Task WaitAsync(int milliseconds)
    {
        await Task.Delay(milliseconds);
    }
    public async Task<bool> AttackChessAsync(Lattice lattice, BaseChessDateSo chessDate)
    {
        EventCenter.GetInstance().EventTrigger("SpotlightClear");
        Settings.canBeUsed = false;
        await WaitAsync(120);
        EventCenter.GetInstance()
            .EventTrigger<Lattice, Color,Color>("ShowAttackTargetLattice", 
                lattice, Settings.canAttack,Settings.isInAttackRange);
        targetLattice = null;
        targetLattice = await WaitSelectAsync();
        EventCenter.GetInstance().EventTrigger("ClearTargetLattice");
        if (targetLattice && targetLattice != lattice)
        {
            ChessManager.GetInstance().Damage(lattice.position, targetLattice.position);
            Settings.canBeUsed = true;
            return true;
        }else if (targetLattice == lattice)
        {
            print(ClickManager.GetInstance().currentLattice);
            Settings.canBeUsed = true;
            return true;
        }
        else
        {
            Settings.canBeUsed = true;
            //为空,代表获取目标格子失败,返回上一步
            return false;
        }
    }
    
}